$(document).ready(function() {
    var ctx = $("#ctx").val(); //获取服务器地址

    /***************************    客户账号管理列表页    ***************************/
    //点击角色更改对应的权限
    //初始页面时传值
    $("input[name='sysType']").each(function() {
        if ($(this).attr("checked") == "checked") {
            getid = $(this).attr("class");
            splitgetid = getid.split(" ");
            roleid = splitgetid[0];

            url = ctx + "/back/main/client-account/getRoleResource?roleId=" + roleid;
            $.ajax({
                async: false,
                traditional: true,
                type: "POST",
                url: url,
                data: {
                    "id": roleid
                },
                success: function(data) {
                    nowresource = data;
                    for (i = 0; i < nowresource.length; i++) {
                        thisval = nowresource[i].id;
                        thisname = nowresource[i].name;
                        $(".autorityType").append("<input class='input-radio' name='power' type='checkbox' checked='checked' value='" + thisval + "'/><span class='input-radio-span powerspan'>" + thisname + "</span>");
                    }
                }
            });
        }
    });



    //点击系统类型传值
    $("input[name='sysType']").click(function() {
        getid = $(this).attr("class");
        splitgetid = getid.split(" ");
        roleid = splitgetid[0];
        url = ctx + "/back/main/client-account/getRoleResource?roleId=" + roleid;
        $.ajax({
            async: false,
            traditional: true,
            type: "POST",
            url: url,
            data: {
                "id": roleid
            },
            success: function(data) {
                nowresource = data;
                $(".autorityType input[name='power']").remove();
                $(".powerspan").remove();
                for (i = 0; i < nowresource.length; i++) {
                    thisval = nowresource[i].id;
                    thisname = nowresource[i].name;
                    $(".autorityType").append("<input class='input-radio' name='power' type='checkbox' checked='checked' value='" + thisval + "'/><span class='input-radio-span powerspan'>" + thisname + "</span>");
                }
            }
        });
    });
    //状态全部、媒体、需求方
    if ($("#sysType").val() == 0 || $("#sysType").val() == "") {
        $("#selectBar_clientaccount a:first").addClass("selectBar_change");
    }
    $("#selectBar_clientaccount a").each(function() {
        var value = $(this).attr("value");
        if ($("#sysType").val() == value) {
            $(this).addClass("selectBar_change").siblings('.selectBar_change').removeClass('selectBar_change');
        }
    });
    $("#selectBar_clientaccount a").click(function() {
        $("#sysType").val($(this).attr("value"));
        refreshData();
    });

    //开启,暂停
    $("#btn-enable,#btn-disable").click(function() {
        if ($(this).attr("id") == "btn-enable") {
            url = ctx + "/back/main/client-account/enable";
        } else if ($(this).attr("id") == "btn-disable") {
            url = ctx + "/back/main/client-account/disable";
        }
        singleOper($(this), url);
    });

    //批量开启,批量暂停
    $("#all-btn-enable,#all-btn-disable").click(function() {
        if ($(this).attr("id") == "all-btn-enable") {
            url = ctx + "/back/main/client-account/enable";
        } else if ($(this).attr("id") == "all-btn-disable") {
            url = ctx + "/back/main/client-account/disable";
        }
        batchOpear($(this), url);
    });

    /***************************    创建，编辑客户账号    ***************************/
    if ($("#sysType").val() == 2) {
        $(".hideOperatorAccount").css("display", "block");
        $(".hideAdverstierAccount").css("display", "none");
    } else if ($("#sysType").val() == 3) {
        $(".hideOperatorAccount").css("display", "none");
        $(".hideAdverstierAccount").css("display", "block");
    }

    //点击媒体显示银行账户
    $("#input-radio-oper").click(function() {
        $(".hideOperator").css("display", "block");
        $(".hideAdverstier").css("display", "none");
        $("#title").attr("verify", "text/255/0/0");
        $("#bank").attr("verify", "text/255/0/0");
        $("#bankAccountName").attr("verify", "text/255/0/0");
        $("#bankAccount").attr("verify", "text/255/0/0");
        $(".hideOperatorAccount").css("display", "block");
        $(".hideAdverstierAccount").css("display", "none");
        $("#type").val("");
    });
    //点击需求方显示发票抬头
    $("#input-radio-adver").click(function() {
        $(".hideAdverstier").css("display", "block");
        $(".hideOperator").css("display", "none");
        $("#title").attr("verify", "text/255/0/0");
        $("#bank").attr("verify", "text/255/0/0");
        $("#bankAccountName").attr("verify", "text/255/0/0");
        $("#bankAccount").attr("verify", "text/255/0/0");
        $(".hideOperatorAccount").css("display", "none");
        $(".hideAdverstierAccount").css("display", "block");
        $("#type").val("");
    });

    //初始校验表单
    if ($("#validateForm").html()) {
        $("#validateForm").autovalidate();
    }

    $("input[name='type']").click(function() {
        $("#type").val($(this).val());
    });

    $("#footBtn .btn-save").click(function() {
        if ($("#type").val() == "") {
            bootbox.alert("请选择账号类型！");
            return false;
        }
        if ($("#accountId").val() == "") { //创建账号时校验账号是否重复
            var flag = isExistName(); //判断账号名称是否重复
            if (flag) {
                return false;
            }
        }
        if ($("#ensurePassword").val() != "" && $("#ensurePassword").val() != $("#password").val()) {
            $("#ensurePassword").css("box-shadow", "0 0 6px #ff0000").attr('title', '确认密码必须与密码一致！');
            $("#ensurePassword").parent("span").parent("div").find("span.spanVaildate").html("确认密码必须与密码一致！");
            return false;
        }
        if (!$("#validateForm").validate()) {
            return false;
        }
        $("#validateForm").submit();
        return false;
    });

    $("#footBtn .btn-cancel").click(function() {
        window.location.href = ctx + "/back/main/client-account/list";
    });

    //权限控制
    if ($(".power-edit").html()) {
        var getPower = $("input[name='getPower']").val();
        var powerArr = getPower.split(",");
        var checkboxs = $("input[name='power']");
        checkboxs.each(function() {
            $(this).prop('checked', false);
            for (var i = 0; i < powerArr.length; i++) {
                if ($(this).val() == powerArr[i]) {
                    $(this).prop('checked', true);
                }
            }
        });
    }
    //个人信息取消按钮
    $("#btn-cancel-account").unbind('click').click(function() {
        location.href = ctx + "/back/main/dashboard";
    });

    $("#accountName").blur(function() {
        if ($(this).val() != "") {
            var reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            if ($(this).val().match(reg) != null) {
                $(this).css("box-shadow", "none").attr('title', '');
                $(this).parent("div").find("span.spanVaildate").html("");
                isExistName();
            } else {
                $(this).css("box-shadow", "0 0 6px #ff0000").attr('title', '格式必须为邮箱类型， 如: example@email.com');
                $(this).parent("div").find("span.spanVaildate").html("格式必须为邮箱类型， 如: example@email.com");
                return false;
            }
        } else {
            $(this).css("box-shadow", "none");
        }
    });

    $("#accountName").focus(function() {
        $(this).css("box-shadow", "0 0 6px #ff0000");
    });

    //显示密码点击事件
    $("#input-password-create").click(function() {
        if ($(this).attr("checked")) {
            $("#password-span").html('<input class="input-text" tabindex="2" id="password" name="password" type="text" value="' + $("#password").val() + '" verify="unspecial/100/1/0"/>');
            $("#ensurePassword-span").html('<input class="input-text" tabindex="3" id="ensurePassword" name="ensurePassword" type="text" value="' + $("#ensurePassword").val() + '" verify="unspecial/100/1/0"/>');
        } else {
            $("#password-span").html('<input class="input-text" tabindex="2" id="password" name="password" type="password" value="' + $("#password").val() + '" verify="unspecial/100/1/0"/>');
            $("#ensurePassword-span").html('<input class="input-text" tabindex="3" id="ensurePassword" name="ensurePassword" type="password" value="' + $("#ensurePassword").val() + '" verify="unspecial/100/1/0"/>');
        }
        //改变密码框样式时触发
        $("#ensurePassword").blur(function() {
            validPassword();
        });
    });

    //修改密码点击事件
    $("#input-password-edit").click(function() {
        if ($(this).attr("checked")) {
            $("#password").attr("disabled", false);
            $("#ensurePassword").attr("disabled", false);
            $("#password").attr("verify", "unspecial/100/1/0");
            $("#ensurePassword").attr("verify", "unspecial/100/1/0");
        } else {
            $("#password").val("");
            $("#ensurePassword").val("");
            $("#password").attr("disabled", true);
            $("#ensurePassword").attr("disabled", true);
            $("#password").attr("verify", "unspecial/100/0/0");
            $("#ensurePassword").attr("verify", "unspecial/100/0/0");
            $("#password").css("box-shadow", "none").attr('title', '');
            $("#password").parent("span").parent("div").find("span.spanVaildate").html("");
            $("#ensurePassword").css("box-shadow", "none").attr('title', '');
            $("#ensurePassword").parent("span").parent("div").find("span.spanVaildate").html("");
        }
    });

    //确认密码与密码一致
    $("#ensurePassword").blur(function() {
        validPassword();
    });

    $("#ensurePassword, #password").focus(function() {
        $(this).css("box-shadow", "0 0 6px #ff0000");
    });

    $("#ensurePassword, #password").blur(function() {
        $(this).css("box-shadow", "none");
    });

    function validPassword() {
        var password = $("#password").val();
        var ensurePassword = $("#ensurePassword").val();
        if (ensurePassword != "") {
            if (ensurePassword != password) {
                $("#ensurePassword").css("box-shadow", "0 0 6px #ff0000").attr('title', '确认密码必须与密码一致！');
                $("#ensurePassword").parent("span").parent("div").find("span.spanVaildate").html("确认密码必须与密码一致！");
                return false;
            } else {
                $("#ensurePassword").css("box-shadow", "none").attr('title', '');
                $("#ensurePassword").parent("span").parent("div").find("span.spanVaildate").html("");
            }
        }
    }

    /***************************    账号关联    ***************************/

    $("#btn-correlate").live("click", function() {
        var agentId = $(this).attr("valueAgentId");
        var operatorId = $(this).attr("valueOperatorId");
        $.post(ctx + "/back/main/client-account/cancelcorrelation", {
            agentId: agentId,
            operatorId: operatorId
        }, function() {
            refreshData();
        });
    });

    //请选择媒体
    if ($("#main_operatorListUl").html()) {
        $("#son_operatorListUl").hide();
        var url = ctx + "/widget/selector/provide/operator?parentId=1";
        getSelectData("operatorListUl_span", "son_operatorListUl", "operatorListUl_box", -1, "请选择运营商", url, "operatorList");
        $('ul#son_operatorListUl li').live("click", function() {
            $(this).parents('li').find('span').text($(this).text());
            $("#selectedOperatorId").val($(this).attr("value"));
            $('#son_operatorListUl').hide(); //ul隐藏
        });
    }

    //请选择代理商
    if ($("#main_agentUl").html()) {
        $("#son_agentListUl").hide();
        var url = ctx + "/widget/selector/provide/adv-agent";
        getSelectData("agentListUl_span", "son_agentListUl", "agentListUl_box", -1, "请选择代理商", url, "advAgentsList");
        $('ul#son_agentListUl li').live("click", function() {
            $(this).parents('li').find('span').html($(this).html());
            $("#selectedAgentId").val($(this).attr("value"));
            $('#son_agentListUl').hide(); //ul隐藏
        });
    }
    //保存按钮
    $("#btn-correlation-save").click(function() {
        if ($("#selectedOperatorId").val() == -1 || $("#selectedOperatorId").val() == "") {
            bootbox.alert("请选择需要关联的运营商！");
            return false;
        }
        if ($("#selectedAgentId").val() == -1 || $("#selectedAgentId").val() == "") {
            bootbox.alert("请选择需要关联的代理商！");
            return false;
        }
        aa();
        return false;
    });

    //取消按钮
    $("#btn-correlation-cancel").click(function() {
        window.location.href = ctx + "/back/main/client-account/correlation";
    });
});

function uploadFileHandler(elemIdObjId, objId, fileStrObj, objDivId) {
    initFile($("#" + elemIdObjId), $("#" + objId).val());
    if ($("#" + objId).val() != "" && $("#" + objId).val() != "noFiles") {
        $('#' + fileStrObj).html("预览");
    }
    $('#' + fileStrObj).unbind('click').click(function() {
        if ($(this).html() == "上传") {
            getUploadFile($(this), elemIdObjId, objDivId, objId, null, null, null);
        } else if ($(this).html() == "预览") {
            if ($("#" + objId).val() != "") {
                bootbox.dialog({
                    message: '<img src="' + $("#" + objId).val() + '"/>',
                    title: "浏览素材",
                    locale: 'zh_CN'
                });
            }
        }
    });
}

function exportExcel_list() {
    var searchValue = $("#searchValue").val();
    if (searchValue == "请输入关键字") {
        searchValue = "";
    }
    var param = "?sysType=" + $("#sysType").val() + "&searchValue=" + searchValue;
    $("#exportExcel").attr("href", $("#ctx").val() + "/back/main/client-account/exportDataReportExcel" + param);
    return false;
}

function isExistName() {
    var flag = false;
    var clientAccountName = $("#accountName").val();
    $.ajax({
        type: "POST",
        url: $("#ctx").val() + "/back/main/client-account/isExist",
        async: false,
        data: {
            clientAccountName: clientAccountName
        },
        success: function(data) {
            if (data == "YES") {
                $("#accountName").css("box-shadow", "0 0 6px #ff0000").attr('title', '你输入的账号已存在！');
                $("#accountName").parent("div").find("span.spanVaildate").html("你输入的账号已存在！");
                flag = true;
            } else {
                $("#accountName").css("box-shadow", "none").attr('title', '');
                $("#accountName").parent("div").find("span.spanVaildate").html("");
                flag = false;
            }
        }
    });
    return flag;
}

function getSelectData(target_spanId, target_sonulId, target_boxId, defaultValue, defaultName, url, paramValue) {
    $("#" + target_sonulId).append("<li value=" + defaultValue + ">" + defaultName + "</li>");
    $.getJSON(url, function(data) {
        var data_1 = data[paramValue];
        $.each(data_1, function(key, val) {
            $("#" + target_sonulId).append('<li value=' + val.value + '>' + val.label + '</li>');
        });
    });
    $("#" + target_spanId).on("click", function() {
        if ($("#" + target_sonulId).height() > 210) {
            $("#" + target_sonulId).addClass("son_ul_change");
        }
        $("#" + target_sonulId).show(); //ul显示
    });
    $("#" + target_boxId).mouseleave(function() {
        $("#" + target_sonulId).hide(); //ul隐藏
        $("#" + target_sonulId).removeClass("son_ul_change");
    });
}

function aa() {
    var c = $("#selectedOperatorId").val();
    var url = $("#ctx").val() + "/back/main/client-account/is_exit";
    console.log(url);
    $.ajax({
        type: "POST",
        url: url,
        data: {
            operatorId: c
        },
        success: function(data) {
            if (data == "YES") {
                bootbox.alert("该运营商已存在关联，请先检查选择是否正确或取消关联");
                return false;
            } else {
                $("#correlationForm").submit();
            }
        }
    });
}

//创建账号

function create_acc() {
    var selected_item = $(".selectBar_change").attr("id");
    var ar_selected_item = selected_item.split("_");
    window.location.href = $("#ctx").val() + "/back/main/client-account/create?sysType=" + ar_selected_item[1];
}